<template>
    <div class="box">
        <!-- 头部搜索模块 -->
        <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addDrawerForm"
            :buttonList="buttonList" />
        <!-- 中间表格模块 -->
        <BaseTable :data="portInventorytableData" :columns="portInventoryDataColumns" @details="selectDataList"
            :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>

        <div class="page">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
        </div>
        <!-- 添加港存 -->
        <el-drawer :before-close="handleClose" :visible.sync="drawerInner" direction="rtl" size="60%">
            <template slot="title">
                <div>
                    <div>添加港存</div>
                    <div style="display: flex;float: right;margin-top: -20px;margin-right: 30px;">
                        <el-form :model="lottingForm" size="small" label-width="80px">
                            <el-form-item label="选择票货">
                                <el-input v-model="portStorage" style="width: 250px;" :disabled="true"></el-input>
                            </el-form-item>
                        </el-form>
                        <el-button style="margin-left: 50px;" size="mini" type="primary" @click="addLotting">添加</el-button>
                    </div>
                </div>
            </template>
            <el-form :model="lottingForm" ref="basisRulesRef" size="small">
                <el-table :data="lottingForm.lottingDetailedData" border>
                    <el-table-column label="库场">
                        <template slot-scope="scope">
                            <el-form-item :prop="`lottingDetailedData[${scope.$index}].storehouseId`"
                                :rules="[{ required: true, message: '库场不能为空' }]">
                                <el-select v-model="scope.row.storehouseId"
                                    @change="changeStorehouseId(scope.$index, scope.row.storehouseId)">
                                    <el-option v-for="item in storeHouseList" :key="item.storehouseId"
                                        :label="item.storehouseName" :value="item.storehouseId"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="货位">
                        <template slot-scope="scope">
                            <el-form-item>
                                <el-select v-model="scope.row.locationId"
                                    @change="changeValue(scope.$index, scope.row.locationId)">
                                    <el-option v-for="item in scope.row.locationList" :key="item.locationId"
                                        :label="item.locationNo" :value="item.locationId"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="垛号">
                        <template slot-scope="scope">
                            <el-form-item :prop="`lottingDetailedData[${scope.$index}].stackPosition`"
                                :rules="[{ required: true, message: '垛号不能为空' }]">
                                <el-input v-model="scope.row.stackPosition"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="件数">
                        <template slot-scope="scope">
                            <el-form-item :prop="`lottingDetailedData[${scope.$index}].quantity`"
                                :rules="[{ required: true, message: '件数不能为空' }]">
                                <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                    v-model.number="scope.row.quantity"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="重量">
                        <template slot-scope="scope">
                            <el-form-item :prop="`lottingDetailedData[${scope.$index}].ton`"
                                :rules="[{ required: true, message: '件数不能为空' }]">
                                <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                    v-model.number="scope.row.ton"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="体积">
                        <template slot-scope="scope">
                            <el-form-item :prop="`lottingDetailedData[${scope.$index}].volume`"
                                :rules="[{ required: true, message: '体积不能为空' }]">
                                <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                    v-model="scope.row.volume"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="出入库">
                        <template slot-scope="scope">
                            <el-form-item>
                                <el-select v-model="scope.row.inOutType">
                                    <el-option v-for="item in inOutDepot" :key="item.value" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-link type="danger"
                                @click.native.prevent="deleteCargoInfo(scope.$index, lottingForm.lottingDetailedData)">删除</el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div class="demo-drawer__footer">
                <el-button type="primary" @click="submitInner()" :loading="ineerLoading" size="small">
                    {{ ineerLoading ? "提交中 ..." : "保 存" }}
                </el-button>
                <el-button size="small" @click="drawerInner = false">取消</el-button>
            </div>
        </el-drawer>
        <!-- 进出明细 -->
        <el-drawer :before-close="handleClose" :visible.sync="showDetailed" direction="rtl" size="90%">
            <template slot="title">
                <div>
                    <div>进出明细</div>
                </div>
            </template>
            <div class="topDiv">
                <i class="el-icon-warning" style="color: rgb(139, 198, 240); margin-left: 10px;"></i>
                <span style="line-height: 40px; font-size: 15px; margin-left: 10px;">{{ portStorage }}</span>
            </div>
            <el-container>
                <el-aside width="50%">
                    <div style="font-size: 16px; height: 40px; background-color: #e1e4eb;">
                        <div style="line-height: 40px;">
                            <span style="margin-left: 10px;">入库记录</span>
                            <span style="margin-left: 10px;">{{ inSummaryData.quantity ? inSummaryData.quantity : 0 }}</span>件
                            <span style="margin-left: 10px;">{{ inSummaryData.ton ? inSummaryData.ton : 0 }}</span>吨
                            <span style="margin-left: 10px;">{{ inSummaryData.volume ? inSummaryData.volume : 0 }}</span>方
                        </div>

                    </div>
                    <BaseTable :data="intoStorehouse" :columns="intoStorehouseColumns" :tableHeight="tableHeight1"
                        :pagination="false" :loading="drawerLoading">
                    </BaseTable>
                </el-aside>
                <el-main style="margin-top: -20px;">
                    <div style="font-size: 16px; height: 40px; background-color: #e1e4eb;">
                        <div style="line-height: 40px;">
                            <span style="margin-left: 10px;">出库记录</span>
                            <span style="margin-left: 10px;">{{ outSummaryData.quantity ? Math.abs(outSummaryData.quantity) :
                                0 }}</span>件
                            <span style="margin-left: 10px;">{{ outSummaryData.ton ? Math.abs(outSummaryData.ton) :
                                0 }}</span>吨
                            <span style="margin-left: 10px;">{{ outSummaryData.volume ? Math.abs(outSummaryData.volume) :
                                0 }}</span>方
                        </div>

                    </div>
                    <BaseTable :data="outStorehouse" :columns="outStorehouseColumns" @details="selectDataList"
                        :tableHeight="tableHeight1" :pagination="false" :loading="drawerLoading">
                    </BaseTable>
                </el-main>
            </el-container>
            <div class="demo-drawer__footer">
                <el-button size="small" @click="showDetailed = false">取消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/yardTally/portStorage'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      ineerLoading: false,
      drawerLoading: false,
      tableHeight: window.innerHeight - 200,
      tableHeight1: window.innerHeight - 190,
      // 搜索框显示对象
      selectObject: [
        {
          name: '库场',
          type: 'select',
          modelName: 'storehouseId',
          selectLabel: 'storehouseName',
          selectValue: 'storehouseId',
          selectData: []
        },
        {
          name: '货主',
          type: 'select',
          modelName: 'cargoOwnerId',
          selectLabel: 'customerName',
          selectValue: 'customerId',
          selectData: []
        },
        {
          name: '垛号',
          type: 'input',
          modelName: 'stackPosition'
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '添加场存', icon: 'el-icon-plus', type: 'primary', click: () => this.addDrawerForm, permission: 'yardDataSubsystem:busCargo:insert' },
        { label: '查看明细', icon: 'el-icon-tickets', type: 'primary', click: () => this.addDetailed, permission: 'yardDataSubsystem:busCargo:insert' }
      ],
      portInventoryDataColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'cargoOwnerName', label: '货主', isShort: true, width: '80' },
        { prop: 'cargoAgentName', label: '货代', isShort: true, width: '80' },
        { prop: 'cargoName', label: '货名' },
        { prop: 'packing', label: '包装', width: '80' },
        { prop: 'storehouseName', label: '库场' },
        { prop: 'locationNo', label: '货位' },
        { prop: 'stackPosition', label: '垛位', width: '220' },
        { prop: 'quantity', label: '件数', width: '80' },
        { prop: 'ton', label: '重量' },
        { prop: 'volume', label: '体积' }
      ],
      portInventorytableData: [],
      storeHouseList: [],
      locationList: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0,
        storehouseId: '',
        cargoOwnerId: '',
        stackPosition: ''
      },
      detailsData: null,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      drawerInner: false,
      showDetailed: false,
      lottingForm: {
        lottingDetailedData: []
      },
      portStorage: '',
      intoStorehouseColumns: [
        { prop: 'inOutDate', label: '日期' },
        { prop: 'inOutTime', label: '班次' },
        { prop: 'processNameZhu', label: '操作过程' },
        { prop: 'processName', label: '子过程' },
        { prop: 'sourcePosition', label: '从' },
        { prop: 'targetPosition', label: '到' },
        { prop: 'quantity', label: '件数' },
        { prop: 'ton', label: '重量' },
        { prop: 'remark', label: '备注' }
      ],
      intoStorehouse: [],
      outStorehouseColumns: [
        { prop: 'inOutDate', label: '日期' },
        { prop: 'inOutTime', label: '班次' },
        { prop: 'processNameZhu', label: '操作过程' },
        { prop: 'processName', label: '子过程' },
        { prop: 'sourcePosition', label: '从' },
        { prop: 'targetPosition', label: '到' },
        { prop: 'quantity', label: '件数' },
        { prop: 'ton', label: '重量' },
        { prop: 'remark', label: '备注' }
      ],
      inOutDepot: [{
        value: '1',
        label: '入库'
      }, {
        value: '2',
        label: '出库'
      }],
      outStorehouse: [],
      inSummaryData: {},
      outSummaryData: {}
    }
  },
  async activated() {
    this.getlistCustomer()
    this.getStorehouse()
  },
  computed: {
  },
  methods: {
    // 获取库场信息
    getStorehouse() {
      publicapi.queryStorehouseNameByType('').then(res => {
        this.storeHouseList = res.data.data
        this.selectObject[0].selectData = this.storeHouseList
      })
    },
    // 查询货主
    async getlistCustomer() {
      await publicapi.getlistCustomer().then(res => {
        if (res.data.code == '0000') {
          this.locationList = res.data.data
          this.selectObject[1].selectData = this.locationList
        }
      })
    },
    // 获取数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.portInventorytableData = res.data.data.pages
          this.portInventorytableData.forEach(item => {
            item.packing = item.packing == '1' ? '散' : item.packing == '2' ? '件' : '无'
          })
          this.loading = false
        }
      })
    },
    /**
         * 添加港存
         */
    addDrawerForm() {
      if (!this.detailsData) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.lottingForm.lottingDetailedData = []
    },
    /**
         * 进出明细
         */
    async addDetailed() {
      if (!this.detailsData) {
        return this.$message.warning('请选择一条数据')
      }
      this.inSummaryData = {}
      this.outSummaryData = {}
      if (!this.showDetailed) {
        this.showDetailed = true
      }
      const data = {
        id: this.detailsData.id,
        storehouseId: this.detailsData.storehouseId,
        locationId: this.detailsData.locationId,
        stackPosition: this.detailsData.stackPosition,
        inOutType: 1
      }
      await api.getDataById(data).then(res => {
        if (res.status == '200') {
          this.intoStorehouse = res.data.data
        }
      })
      await api.getSummaryById(data).then(res => {
        if (res.status == '200') {
          if (res.data.data) {
            this.inSummaryData = res.data.data
          }
        }
      })
      const msg = {
        id: this.detailsData.id,
        storehouseId: this.detailsData.storehouseId,
        locationId: this.detailsData.locationId,
        stackPosition: this.detailsData.stackPosition,
        inOutType: 2
      }
      await api.getDataById(msg).then(res => {
        if (res.status == '200') {
          this.outStorehouse = res.data.data
          this.outStorehouse.forEach(item => {
            item.quantity = Math.abs(item.quantity)
            item.ton = Math.abs(item.ton)
            item.quantity = Math.abs(item.quantity)
          })
        }
      })
      await api.getSummaryById(msg).then(res => {
        if (res.status == '200') {
          if (res.data.data) {
            this.outSummaryData = res.data.data
          }
        }
      })
      // this.$nextTick(()=>{
      //    this.drawerLoading = false
      // })
    },
    // 选中数据
    selectDataList(val) {
      this.portStorage = ''
      this.detailsData = null
      this.detailsData = val
      this.portStorage = this.detailsData.cargoOwnerName + '/' + this.detailsData.cargoAgentName + '/' + this.detailsData.cargoName + '/' + this.detailsData.packing + '/' + this.detailsData.shipvoyageName
    },
    // 删除
    deleteCargoInfo(index, rows) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rows.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
         * 新建、编辑保存
         */
    submitInner() {
      if (this.lottingForm.lottingDetailedData.length == 0) {
        return this.$message.error('至少包含一条数据')
      }
      for (let i = 0; i < this.lottingForm.lottingDetailedData.length; i++) {
        if (this.lottingForm.lottingDetailedData[i].quantity < 0 || this.lottingForm.lottingDetailedData[i].ton < 0 || this.lottingForm.lottingDetailedData[i].volume < 0) {
          return this.$message.error('每条数据件数、重量、体积不能小于0')
        }
        // if(this.lottingForm.lottingDetailedData[i].quantity == 0 && this.lottingForm.lottingDetailedData[i].ton == 0 && this.lottingForm.lottingDetailedData[i].volume == 0){
        //     return this.$message.error('每条数据件数、重量、体积不能同时为0')
        // }else{
        //     if(Number(this.lottingForm.lottingDetailedData[i].quantity) > 0 && Number(this.lottingForm.lottingDetailedData[i].ton) > 0 && Number(this.lottingForm.lottingDetailedData[i].volume) > 0){
        // }else if(this.lottingForm.lottingDetailedData[i].quantity < 0 && this.lottingForm.lottingDetailedData[i].ton < 0 && this.lottingForm.lottingDetailedData[i].volume < 0){
        // }else{
        //     return this.$message.error('每条数据件数、重量、体积需要满足同时大于或同时小于0')
        // }
        // }
      }
      this.$refs.basisRulesRef.validate((valid) => {
        if (valid) {
          api.updateData(this.lottingForm.lottingDetailedData).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.getData()
              this.detailsData = null
            }
          })
        }
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsData = null
      this.getData()
    },
    // 添加明细信息
    addLotting() {
      const data = {
        cargoInfoId: this.detailsData.id,
        storehouseId: '',
        storehouseName: '',
        locationId: '',
        locationNo: '',
        stackPosition: '',
        quantity: '',
        ton: '',
        volume: '',
        inOutType: '',
        locationList: []
      }
      this.lottingForm.lottingDetailedData.push(data)
    },
    async changeStorehouseId(index, row) {
      this.lottingForm.lottingDetailedData[index].locationId = ''
      this.lottingForm.lottingDetailedData[index].storehouseName = this.storeHouseList.filter(item => item.storehouseId == row)[0].storehouseName
      await publicapi.getStorehouseLocation(row).then(res => {
        if (res.data.code == '0000') {
          this.lottingForm.lottingDetailedData[index].locationList = res.data.data
        }
      })
    },
    // 下拉框数据
    changeValue(index, val) {
      this.lottingForm.lottingDetailedData[index].locationNo = this.lottingForm.lottingDetailedData[index].locationList.filter(item => item.locationId == val)[0].locationNo
    },
    async handleDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDelete(id).then(res => {
          if (res.data.code === '0000') {
            this.getData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.detailsData = null
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.detailsData = null
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.showDetailed) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
    justify-content: space-between;
    display: flex;
    background: #ffffff;
    border: 1px solid #e1e4eb;
    border-bottom: 0;
    border-left: none;
    height: 50px;
    position: relative;
    align-items: center;
    padding-left: 14px;
    padding-right: 20px;
}

.input_box {
    display: flex;
}

.page {
    background: #ffffff;
    text-align: right;
    border-radius: 0 0 4px 4px;
    padding: 5px 20px;
}

/deep/.el-tabs--border-card>.el-tabs__content {
    padding: 0 !important;
}

//抽屉底部样式
/deep/ .el-drawer__header {
    margin-bottom: -10px;
    padding: 16px;
    border-bottom: 1px solid gainsboro;
}

.demo-drawer__footer {
    text-align: right;
    padding-right: 20px;
    border-top: 1px solid #c8cfde;
    background-color: #f5f7fa;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    line-height: 50px;
}

.box {
    background: #ffffff;
    border: 1px solid #e1e4eb;
    border-radius: 4px 4px 0 0;
    border-top: none;
}

.el-form-item--small.el-form-item {
    margin-bottom: 0px;
}

.topDiv {
    height: 40px;
    background-color: rgb(226, 246, 254);
}</style>
